package db_server_sqlserver

import (
	// "database/sql"
	"PackingScanApp/models"
	"errors"
	"fmt"

	"strconv"
	"strings"
)

//查询测试，
func SelectTest() {
	var msqsql MSSql

	msqsql.NewMSsql()
	defer msqsql.CloseMSsql()

	rows, err := msqsql.Conn.QueryContext(msqsql.Ctx,
		"SELECT FInterID FROM PORequest where FInterID ="+"38")

	defer rows.Close()

	if err != nil {
		fmt.Println(err)
		panic(err)
	}

	var FInterID int

	if rows.Next() {
		rows.Scan(&FInterID)
		fmt.Println(strconv.Itoa(FInterID))
	} else {
	}
}

//查询IBB产品 是否有码,1有码
func SelectBarcodeParmater_Num(barcode string) int {
	var msqsql MSSql

	msqsql.NewMSsql()
	defer msqsql.CloseMSsql()

	rows, err := msqsql.Conn.QueryContext(msqsql.Ctx,
		`SELECT count(*) as CountNum from t_barcodeParmater where barcode='`+barcode+`'`)

	defer rows.Close()

	if err != nil {
		panic(err)
	}

	var CountNum int

	if rows.Next() {
		rows.Scan(&CountNum)
		//fmt.Println(strconv.Itoa(CountNum))
	} else {
	}

	return CountNum
}

//查询LBB产品新厂 是否有码，1有码
func SelectBarcodeParmaterLBB_Num(barcode string) int {
	var msqsql MSSql

	msqsql.NewMSsql()
	defer msqsql.CloseMSsql()

	rows, err := msqsql.Conn.QueryContext(msqsql.Ctx,
		`SELECT count(*) as CountNum from t_barcodeParmater_Lbb where barcode='`+barcode+`'`)

	defer rows.Close()

	if err != nil {
		panic(err)
	}

	var CountNum int

	if rows.Next() {
		rows.Scan(&CountNum)
		//fmt.Println(strconv.Itoa(CountNum))
	} else {
	}

	return CountNum
}

//取得ICOM
func SelectICOM_Data(fBillNo string) models.ICOM_Data {
	var msqsql MSSql

	msqsql.NewMSsql()
	defer msqsql.CloseMSsql()

	sql := ` SELECT ICMO.FBillNo as Fbillno,t_ICItem.FNumber as Fnumber,t_ICItem.FName as FName, t_ICItem.FUnitPackageNumber as Sumnumber,ICMO.Fqty as Fqty from ICMO 
			LEFT JOIN t_icitem on ICMO.FItemID=t_icitem.FItemID where FBillNo='` + fBillNo + `';`
	rows, err := msqsql.Conn.QueryContext(msqsql.Ctx, sql)

	defer rows.Close()

	if err != nil {
		panic(err)
	}

	var icmo_data models.ICOM_Data
	sumnumber := ""
	fqty := ""

	if rows.Next() {
		rows.Scan(&icmo_data.Fbillno, &icmo_data.Fnumber, &icmo_data.Fname, &sumnumber, &fqty)
		if j1 := strings.LastIndex(sumnumber, "."); j1 > 0 {
			sumnumber = sumnumber[:j1]
		}
		if j2 := strings.LastIndex(fqty, "."); j2 > 0 {
			fqty = fqty[:j2]
		}

		if i, err := strconv.Atoi(sumnumber); err == nil {
			icmo_data.Sumnumber = i
		} else {
			panic(err)
		}

		if i2, err2 := strconv.Atoi(fqty); err2 == nil {
			icmo_data.Fqty = i2
		} else {
			panic(err)
		}
	} else {
		panic(errors.New("sqlserver执行层错误,ICMO没有找到行！"))
	}

	return icmo_data
}
